package cn.tanghom.app.system.service;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.tanghom.app.system.model.Config;
import cn.tanghom.support.db.BaseActiveRecordDao;
import cn.tanghom.support.db.BaseCrudDao;

import com.unbiz.common.lang.BaseObject;


/**
 *  数据字典
 */
public class DisplayMapping  {
   
    static List<Config> toSaveList = new LinkedList<Config>();
    
    public final BaseCrudDao<Config,Long> dao = new BaseCrudDao<Config,Long>("config");

    public List<Config> getAll() {
        return dao.findAll();
    }
    
    public Config findDisplay(String model,String field) {
    	Map<String,Object> params = new HashMap<>();
    	params.put("groupKey", model);
    	params.put("configKey", field);
    	Config dis= dao.findOne("findByParams",params);
    	if(dis == null){
    		dis = new Config();
    		dis.setConfigKey(field);
    		dis.setGroupKey(model);
    	}
    	return dis;
  }
    
    public List<Config> findByModelName(String model) {
    	Map<String,Object> params = new HashMap<>();
    	params.put("groupKey", model);    	
        return dao.findList("findByParams", params);
    }
    
    public void attach(Config config){
    	toSaveList.add(config);    	
    }
    
    public String display(String model,String field) {
      String result = "";     
      if(!field.isEmpty()) {           
    	  Config display =  findDisplay(model, field);         
          if(display==null){
          	try{
          		if(!toSaveList.isEmpty()){ //清内存中的数据
            		for(Config d:toSaveList){
            			dao.saveOrUpdate(d);
            		}
            		toSaveList.clear();
            		display =  findDisplay(model, field);
            	}  				
  			}
  			catch (Exception e2) {	   
  				e2.printStackTrace();
  			}
          	result = display != null ? display.getName() : field;
          }
          else{ 
        	result = display.getName();
          }
      } 
      return result;
  }
}
